package controllers;

import play.mvc.Controller;
import play.mvc.Result;
import services.scanner.ScanSession;
import services.scanner.SystemScan;
import views.html.index;

import java.io.File;
import java.util.List;

public class Application extends Controller {

    private static final String ERROR_MESSAGE = "Error to access the resource. User not allowed!";

    public static Result index(int pwd) {
        String pass = (pwd != 0) ? "" + pwd : session("pwd");
        if (pwd == 0 && session("pwd") == null || pass != null && !getGrant(Integer.valueOf(pass))) {
            play.Logger.debug("user not allowed to access index resource.");
            return notFound(ERROR_MESSAGE);
        }

        play.Logger.debug("user allowed to access index resource.");
        List<String> paths = SystemScan.getRootDirectories();
        return ok(index.render(paths));
    }

    public static Result getAction(String param, int pwd) {
        String pass = (pwd != 0) ? "" + pwd : session("pwd");
        if (pwd == 0 && session("pwd") == null || pass != null && !getGrant(Integer.valueOf(pass))) {
            play.Logger.debug("user not allowed to access dir resource.");
            return notFound(ERROR_MESSAGE);
        }

        play.Logger.debug("user allowed to access dir resource.");
        if (!new File(param).isDirectory()) {
            response().setContentType("application/x-download");
            return ok(new File(param));
        }
        List<String> paths = SystemScan.getPathDirectories(param);
        return ok(index.render(paths));
    }

    public static boolean getGrant(int value) {
        boolean valid = ScanSession.isAuthValid(value);

        if (!valid) {
            session().clear();
            return false;
        }
        session("pwd", "" + value);

        return true;
    }
}
